package com.fesnakj.todos.dao;

import com.fesnakj.todos.jpa.JPAContext;
import com.fesnakj.todos.model.User;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.TypedQuery;
import java.util.List;


public class UserDao {

    private EntityManagerFactory emf = JPAContext.getEMF();

    public List<User> getAllUsers() {
        EntityManager em = emf.createEntityManager();
        TypedQuery<User> query = em.createNamedQuery("User.findAll", User.class);
        List<User> users = query.getResultList();
        em.close();
        return users;
    }

    public void addUser(User user) {
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        em.persist(user);
        em.getTransaction().commit();
        em.close();
    }

    public User findUserById(int id) {
        EntityManager em = emf.createEntityManager();
        User user = em.find(User.class, id);
        em.close();
        return user;
    }

    public boolean userExists(User user) {
        return userExists(user.getId());
    }

    public boolean userExists(int id) {
        return findUserById(id) != null;
    }

    public void removeUser(User user) {
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        User removable = em.find(User.class, user.getId());
        em.remove(removable);
        em.getTransaction().commit();
        em.close();
    }

    public void removeAllUsers() {
        EntityManager em = emf.createEntityManager();
        List<User> users = em.createNamedQuery("User.findAll", User.class).getResultList();
        for (User user : users) {
            em.getTransaction().begin();
            em.remove(user);
            em.getTransaction().commit();
        }
        em.close();
    }

    public int getAllUsersCount() {
        return getAllUsers().size();
    }

}